var parentJson = {};
parentJson.limit=1000;
parentJson.headField="pno,content,meetingtheme,replydate,enddate,plantype,mno,ino,completedate,finishdate,flag,jindu,replycontent,img,backuser,decisionuser,decisionuserid";
parentJson.page=1;
var enddatecalendar = new lCalendar();
var replydatecalendar = new lCalendar();
var url  = location.search;
var theRequest = new Object();  
if ( url.indexOf( "?" ) != -1 ){  
var str = url.substr( 1 ); //substr()方法返回从参数值开始到结束的字符串；  
var strs = str.split( "&" ); 
var plantype=1; 
var thenum = 0;
var thesum = 0;
var mno;
var ino;
var starvalue=0;
for ( var i = 0; i < strs.length; i++ ) {  
theRequest[ strs[ i ].split( "=" )[ 0 ] ] = ( strs[ i ].split( "=" )[ 1 ] );  
}  
}
var aa={};
aa.conditionField = "pno";
aa.conditionValue = theRequest.pno;
aa.conditionOption = "=";
aa.logicalOperator = "and";
parentJson.search=[aa];
var now=getNowFormatDate();
var _config ;
var photoUrl = [];//拍照列表
var now = getDay(0);
var theusername = sessionStorage.getItem("name");
var theuserid = sessionStorage.getItem("userId");
var identity = true;
var tof =true;
console.log(parentJson);




$.ajax({
	url: "../../work_plan_info/getSelectBody"
	,type:'post'
	,async: false
	,contentType: "application/json; charset=utf-8"
	,data:JSON.stringify(parentJson) 
	,dataType:'json'
	,success: function(res){
		console.log(res.data[0]);
		if(res.data[0].decisionuserid!=undefined&&res.data[0].decisionuserid!=undefined){
			identity =(res.data[0].decisionuserid.indexOf(theuserid) != -1);    
		}
        if(!identity){
	      $("#addButton").css({"display": "none"});
          $("#saveButton").css({"display": "none"});	
		}
		plantype=res.data[0].plantype;
		mno=res.data[0].mno;
		ino=res.data[0].ino;
		if(res.data[0].content==undefined){
			content.value="";
		}else{content.value=res.data[0].content;}
		if(res.data[0].enddate==undefined){
			enddate.value="";
		}else{
			enddate.value=res.data[0].enddate;
		}
		if(res.data[0].replydate==undefined){
			replydate.value="";
		}else{
			replydate.value=res.data[0].replydate;
		}
		if(res.data[0].meetingtheme==undefined){
			meetingtheme.value="";
		}else{
			meetingtheme.value=res.data[0].meetingtheme;
		}
		if(res.data[0].flag==undefined){
			flag.value="";
		}else{
			if(res.data[0].flag==9){flag.value="已完成";}
			else if(res.data[0].flag==10){flag.value="未完成";}
			else if(res.data[0].flag==12){flag.value="未回复";}
			else if(res.data[0].flag==500){flag.value="已回复";}
		}
		if(res.data[0].replycontent==undefined){
			replycontent.value="";
		}else{
			replycontent.value=res.data[0].replycontent;
		}
		if(res.data[0].backuser==undefined){
			backuser.value="";
		}else{
			backuser.value=res.data[0].backuser;
		}
		if(res.data[0].decisionuser==undefined){
			decisionuser.value="";
		}else{
			decisionuser.value=res.data[0].decisionuser;
		}
		
				if(res.data[0].img==undefined||res.data[0].img==""){
                     console.log("null");
                }else{
					photoUrl=[];
					photoUrl.push(res.data[0].img);	
					var result=res.data[0].img.split(",");	
					for(var i=0;i<result.length;i++){												  
						$('#wig_img').append('<div class="img_box" id="img_box'+i+'">'
						+'<img alt="100x100" src="'+result[i]+'" onclick="showAllPic(\''+result[i]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						);
					}
				}

	
	}
});
$.ajax({
	url: "../../meeting_info_detail/getevaluate"
	,type:'post'
	,async: false
	,contentType: "application/json; charset=utf-8"
	,data: JSON.stringify({
            "mno": mno,
            "ino": ino,
        })
	,dataType:'json'
	,success: function(res){
		thesum = res.data.length;
		getpingjia(res.data,res.data.length);
		for(var i=0;i<thesum;i++){
			if(res.data[i].pjsj.substring(0,10)==getNowFormatDate()){tof=false;}
		}
	}
});
$.ajax({
	    url: '../../meeting_info_detail/getcontentBody'
		,type:'post'
		,dataType:'json'
		,contentType: "application/json; charset=utf-8"
		,data: JSON.stringify({
            "mno": mno,
            "ino": ino,
        }) 
		,dataType:'json'
		,success: function(res){
			if(identity){
				layui.use(['rate'], function(){
						var rate = layui.rate;
						  rate.render({
					    elem: '#test5'
					    ,text: true
					    ,setText: function(value){ //自定义文本的回调
					      var arrs = {
						        '1': '待提升'
						        ,'2': '待提升'
						        ,'3': '一般'
						        ,'4': '满意'
						        ,'5': '非常满意'
								,'0': '待评'
								,'': '待评'
					      };
						  starvalue = value;
					      this.span.text(arrs[value] || ( value + "星"));
					    }
					  })
					});
			}else{
				layui.use(['rate'], function(){
						var rate = layui.rate;
						  rate.render({
					    elem: '#test5'
					    ,value: res.data[0].rating
					    ,text: true
						,readonly:true
					    ,setText: function(value){ //自定义文本的回调
					      var arrs = {
						        '1': '待提升'
						        ,'2': '待提升'
						        ,'3': '一般'
						        ,'4': '满意'
						        ,'5': '非常满意'
								,'0': '待评'
								,'': '待评'
					      };
						  starvalue = value;
					      this.span.text(arrs[value] || ( value + "星"));
					    }
					  })
					});
			}
					
		}
	
});
$(document).ready(function(){
	$('#name').text(sessionStorage.getItem("name"));
	$('#searchDate').text(now);
	$('#saveButton').on('click',saveInfo);
	$('#addButton').on('click',addform);
	$(document).on('click','div[deleteIndex]',function(){
		var obj = this;
		dd.ready(function(){
			dd.device.notification.confirm({
				message: "确认删除此工作计划吗？",
				title: "提示",
				buttonLabels: ['是', '否'],
				onSuccess : function(result) {
					if(result.buttonIndex == 0){
						$('div[itemDiv="'+$(obj).attr('deleteIndex')+'"]').remove();
					}
				},
				onFail : function(err) {}
			});
		})
	});
});
$('#paizhao').on('click',function(){
	openphoto();
});
//获取当前日期
function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }
//获取当前日期
function getNowFormatDatetime() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
    	var strDate = date.getDate();
		var hour = date.getHours();
		var minutes = date.getMinutes();
		var seconds = date.getSeconds();
    
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }	
		if (hour >= 0 && hour <= 9) {
            hour = "0" + hour;
        }
  		if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
  		if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate + ' '+hour+':'+minutes+':'+seconds;
        return currentdate;
    }
//打开钉钉拍照
function openphoto(){
	if(_config == undefined){
		$.ajax({
			type : "post",
			data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26')}),
			contentType: "application/json; charset=utf-8",
			async: false,
			url : "../../dingding/getconfig",
			dataType : "json",
			success : function(suc) {
//				console.log(suc);
				_config = suc.config;
			}
		}); 
		dd.config({
			agentId : _config.agentid,
			corpId : _config.corpId,
			timeStamp : _config.timeStamp,
			nonceStr : _config.nonceStr,
			signature : _config.signature,
			jsApiList : [ 'runtime.info','biz.util.uploadImage' ]
		});
	}
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: getNowFormatDateTime(),
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
			photoUrl.push(result[0]);
			$('#paizhapoUrl .clearfix').remove()
			$('#paizhapoUrl').append('<div class="wig_img">'
					+'<div class="img_box">'
					+'<img alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
					+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
					+'</div>'
					+'</div>');
			$('#paizhapoUrl').append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
}	
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().parent().index();
	    		$(obj).parent().parent().remove();
	    		photoUrl.splice(index,1);
	    	}
	        
	    },
	    onFail : function(err) {}
	});
	 
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: photoUrl,//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}
function addform(){
   if(tof){
	tof=false;
	var itemDivIndex = $('div[itemDiv]').length;
    $('#f_div').append('<div class="col_box" itemDiv="'+thenum+'">'
    					+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
						+'<h5 id="wentishuomingTitle" class="black">评价'+(itemDivIndex+thesum+1)+'</h5>'
						+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
				    	+'</div>'
						+'<div class="widget-box add_mar_tb7p add_bor_bgrey">'
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'<h5><i class="iconfont">&#xe600;</i>&nbsp;评价内容</h5><span class="red">*</span>'						  
					    +'</div>'
					
						+'<div class="widget-body zhediebox1">'					
						+'<div class="widget-main pd_div" style="padding:0;">'					
						+'<div class="clearfix jy_div" style="padding:0;">'						
						+'<textarea id="evaluate'+thenum+'"  jsonKey="evaluate" name="evaluate" rows="" cols="" class="pull-left add_pad_tb10p add_bor_none" placeholder="请填写评价内容"></textarea>'								
					    +'</div>'						
							+'</div>'						
							+'</div>'					
							+'</div>'				
							+'<div>'			
		                    +'<div class="widget-box add_mar_tb7p ">'
							+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
							+'<h5><i class="iconfont">&#xe609;</i>&nbsp;评价时间</h5><span class="red"></span>'
							+'<input type="text" id="pjsj'+thenum+'" readonly="readonly" placeholder="" jsonKey="pjsj" class="pull-right add_bor_none" autocomplete="off" style="width: 70%;margin-right: 2%;" value="'+getNowFormatDatetime()+'"/>'
							+'</div>'
							+'</div>'
							+'</div>'
							+'		<div class="widget-box add_mar_tb7p">'
							+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
							+'				<h5><i class="iconfont">&#xe609;</i>&nbsp;评价人</h5><span class="red"></span>'
							+'				<input type="text" id="pjr'+thenum+'"  readonly="readonly"  placeholder="" jsonKey="pjr" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%" value="'+theusername+'"/>'
							+'			</div>'
							+'		</div>'
							+'<div>'
							+'</div>');
    thenum++;
	}else{
		alert('每天只能添加一条评价!');
	}
}
function saveInfo(){
	showloading();
			var send = {};
			send.evaluate = '';
			send.rating = starvalue;//$('#star4').text().replace('星',"");
			send.mno = mno;
			send.ino = ino;
			$.ajax({
				url: '../../meeting_info_detail/pingjia'
				,type:'post'
				,dataType:'json'
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(send)  
				,done: function(res){				
				}
			});				
	try {
		var imgStr = "";
		var sendData = {};
		var insertArray = [];
		var updateArray = [];
		var checkFlag = true;
		$('div[itemDiv]').each(function(i,obj){
			var insertJson = {};
			$(obj).find('textarea[jsonKey]').each(function(j,el){
				if($(el).parent().parent().parent().parent().find('span').text() == '*' && $(el).val() == ''){
					alert($(el).parent().parent().parent().parent().find('h5').text()+"为必填项");
					checkFlag = false;
					return false;
				}else{
					var key = $(el).attr('jsonKey');
					insertJson[key] = $(el).val();
					key = null;
				}
			});
			$(obj).find('select[jsonKey]').each(function(j,el){
				if($(el).parent().parent().parent().parent().find('span').text() == '*' && $(el).val() == ''){
					alert($(el).parent().parent().parent().parent().find('h5').text()+"为必填项");
					checkFlag = false;
					return false;
				}else{
					var key = $(el).attr('jsonKey');
					insertJson[key] = $(el).val();
					key = null;
				}
			});
			if(checkFlag){
				$(obj).find('input[jsonKey]').each(function(j,el){
					if($(el).parent().find('span').text() == '*' && $(el).val() == ''){
						alert($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('jsonKey');
						insertJson[key] = $(el).val();
						//console.log(insertJson);
						key = null;
					}
				});
			}else{
				return false;
			}
			insertJson.mno=mno;
			insertJson.ino=ino;
            insertArray.push(insertJson);
		});
		//修改部分
		$('div[editDiv]').each(function(i,obj){
			var updateJson = {};
			$(obj).find('textarea[editKey]').each(function(j,el){
				if($(el).parent().parent().parent().parent().find('span').text() == '*' && $(el).val() == ''){
					alert($(el).parent().parent().parent().parent().find('h5').text()+"为必填项");
					checkFlag = false;
					return false;
				}else{
					var key = $(el).attr('editKey');
					updateJson[key] = $(el).val();
					key = null;
				}
			});
			$(obj).find('select[editKey]').each(function(j,el){
				if($(el).parent().parent().parent().parent().find('span').text() == '*' && $(el).val() == ''){
					alert($(el).parent().parent().parent().parent().find('h5').text()+"为必填项");
					checkFlag = false;
					return false;
				}else{
					var key = $(el).attr('editKey');
					updateJson[key] = $(el).val();
					key = null;
				}
			});
			if(checkFlag){
				$(obj).find('input[editKey]').each(function(j,el){
					if($(el).parent().find('span').text() == '*' && $(el).val() == ''){
						alert($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('editKey');
						updateJson[key] = $(el).val();
						key = null;
					}
				});
			}else{
				return false;
			}
			updateJson.mno=mno;
			updateJson.ino=ino;
            updateArray.push(updateJson);
		});
		sendData.insertArray = insertArray;
		sendData.updateArray = updateArray;
		console.log(sendData);
		if(checkFlag){
			$.ajax({
				url: "../../work_plan_info/addNewpingjia"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.status==1000){
						layer.msg(res.msg);
					}else{
						layer.msg(res.msg,{time:1000},function(){
							//history.go(-1);
							url = "../../mobile_page/work_plan_info/work_content_search";//此处拼接内容
	                        window.location.href = url;
						});
					}
				}
			    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	

	
}
function getpingjia(resdata,length){
	if(length>0){	
		for(var i=0;i<length;i++){
			 $('#a_div').append('<div class="col_box" editDiv="'+thenum+'">'
    					+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
						+'<h5 id="wentishuomingTitle" class="black">评价'+(i+1)+'</h5>'
						//+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
				    	+'</div>'
						+'<div class="widget-box add_mar_tb7p add_bor_bgrey">'
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'<h5><i class="iconfont">&#xe600;</i>&nbsp;评价内容</h5><span class="red">*</span>'						  
					    +'</div>'	
						+'<div class="widget-body zhediebox1">'					
						+'<div class="widget-main pd_div" style="padding:0;">'					
						+'<div class="clearfix jy_div" style="p	adding:0;">'						
						+'<textarea id="evaluate'+thenum+'" '+Istoday(resdata[i].pjsj)+' editKey="evaluate" name="evaluate" rows="" cols="" class="pull-left add_pad_tb10p add_bor_none" placeholder="请填写评价内容">'+resdata[i].evaluate+'</textarea>'								
					    +'</div>'						
							+'</div>'						
							+'</div>'					
							+'</div>'				
							+'<div>'			
		                    +'<div class="widget-box add_mar_tb7p ">'
							+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
							+'<h5><i class="iconfont">&#xe609;</i>&nbsp;评价时间</h5><span class="red"></span>'
							+'<input type="text" id="pjsj'+thenum+'" readonly="readonly" placeholder="" editKey="pjsj" class="pull-right add_bor_none" autocomplete="off" style="width: 70%;margin-right: 2%;" value="'+resdata[i].pjsj+'"/>'
							+'</div>'
							+'</div>'
							+'</div>'
							+'		<div class="widget-box add_mar_tb7p">'
							+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
							+'				<h5><i class="iconfont">&#xe609;</i>&nbsp;评价人</h5><span class="red"></span>'
							+'				<input type="text" id="pjr'+thenum+'" editKey="pjr" readonly="readonly"  placeholder=""  autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%" value="'+resdata[i].pjr+'"/>'
							+'			</div>'
							+'		</div>'
							+'<div>'
							+'</div>');
		}
	}
}
function Istoday(Date1){
	if(Date1.substring(0,10)!=getNowFormatDate()){
		return 'readonly="readonly"'
	}else{return '';}
}